# settings_window.py
import tkinter as tk
from tkinter import ttk, messagebox, colorchooser
import configparser
import os
from settings_applier import apply_settings

class SettingsWindow(tk.Toplevel):
    def __init__(self, parent, settings=None):
        super().__init__(parent)
        self.title("设置")
        self.geometry("450x500")
        self.resizable(False, False)
        self.settings = settings or {}
        
        # 居中显示
        self.transient(parent)
        self.grab_set()
        
        # 配置解析器
        self.config = configparser.ConfigParser()
        self.config_file = "set.ini"
        
        # 加载设置
        self.load_settings()
        
        # 创建界面
        self.create_widgets()
        
        # 设置模态窗口行为
        self.focus_set()
        self.wait_visibility()
        self.grab_set()
    
    def load_settings(self):
        """加载设置文件或使用默认值"""
        if os.path.exists(self.config_file):
            self.config.read(self.config_file, encoding='utf-8')
        else:
            # 默认设置
            self.config['SETTINGS'] = {
                'background_color': '#f0f0f0',
                'foreground_color': '#f0f0f0',
                'text_color': '#000000',
                'transparency': '1.0',
                'always_on_top': 'False'
            }
    
    def save_settings(self):
        """保存设置到文件"""
        # 将透明度值除以100转换为0-1范围
        transparency_value = self.transparency_var.get() / 100.0
        self.config['SETTINGS']['transparency'] = str(transparency_value)
        self.config['SETTINGS']['background_color'] = self.bg_color_var.get()
        self.config['SETTINGS']['foreground_color'] = self.fg_color_var.get()
        self.config['SETTINGS']['text_color'] = self.text_color_var.get()
        self.config['SETTINGS']['always_on_top'] = str(self.topmost_var.get())
        
        with open(self.config_file, 'w', encoding='utf-8') as configfile:
            self.config.write(configfile)
    
    def create_widgets(self):
        # 背景颜色设置
        bg_color_frame = ttk.LabelFrame(self, text="背景颜色", padding=10)
        bg_color_frame.pack(fill=tk.X, padx=10, pady=5)
        
        self.bg_color_var = tk.StringVar(value=self.config['SETTINGS'].get('background_color', '#f0f0f0'))
        
        # 使用标准 tk.Frame 而不是 ttk.Frame 以支持背景颜色
        bg_color_preview = tk.Frame(bg_color_frame, height=30, width=60, relief=tk.SOLID)
        bg_color_preview.pack(side=tk.LEFT, padx=(0, 10))
        bg_color_preview.configure(background=self.bg_color_var.get())
        bg_color_preview._is_color_preview = True  # 标记为颜色预览框
        
        # 显示颜色代码
        bg_color_code_label = ttk.Label(
            bg_color_frame, 
            text=self.bg_color_var.get(), 
            font=("Courier", 10),
            width=10
        )
        bg_color_code_label.pack(side=tk.LEFT, padx=(0, 10))
        
        ttk.Button(
            bg_color_frame, 
            text="选择颜色", 
            command=lambda: self.choose_color(bg_color_preview, bg_color_code_label, self.bg_color_var)
        ).pack(side=tk.LEFT)
        
        # 前景颜色设置
        fg_color_frame = ttk.LabelFrame(self, text="前景颜色（按钮、输入框等）", padding=10)
        fg_color_frame.pack(fill=tk.X, padx=10, pady=5)
        
        self.fg_color_var = tk.StringVar(value=self.config['SETTINGS'].get('foreground_color', '#f0f0f0'))
        
        # 使用标准 tk.Frame 而不是 ttk.Frame 以支持背景颜色
        fg_color_preview = tk.Frame(fg_color_frame, height=30, width=60, relief=tk.SOLID)
        fg_color_preview.pack(side=tk.LEFT, padx=(0, 10))
        fg_color_preview.configure(background=self.fg_color_var.get())
        fg_color_preview._is_color_preview = True  # 标记为颜色预览框
        
        # 显示颜色代码
        fg_color_code_label = ttk.Label(
            fg_color_frame, 
            text=self.fg_color_var.get(), 
            font=("Courier", 10),
            width=10
        )
        fg_color_code_label.pack(side=tk.LEFT, padx=(0, 10))
        
        ttk.Button(
            fg_color_frame, 
            text="选择颜色", 
            command=lambda: self.choose_color(fg_color_preview, fg_color_code_label, self.fg_color_var)
        ).pack(side=tk.LEFT)
        
        # 文本颜色设置
        text_color_frame = ttk.LabelFrame(self, text="文本颜色", padding=10)
        text_color_frame.pack(fill=tk.X, padx=10, pady=5)
        
        self.text_color_var = tk.StringVar(value=self.config['SETTINGS'].get('text_color', '#000000'))
        
        # 使用标准 tk.Frame 而不是 ttk.Frame 以支持背景颜色
        text_color_preview = tk.Frame(text_color_frame, height=30, width=60, relief=tk.SOLID)
        text_color_preview.pack(side=tk.LEFT, padx=(0, 10))
        text_color_preview.configure(background=self.text_color_var.get())
        text_color_preview._is_color_preview = True  # 标记为颜色预览框
        
        # 显示颜色代码
        text_color_code_label = ttk.Label(
            text_color_frame, 
            text=self.text_color_var.get(), 
            font=("Courier", 10),
            width=10,
            foreground=self.text_color_var.get()
        )
        text_color_code_label.pack(side=tk.LEFT, padx=(0, 10))
        
        ttk.Button(
            text_color_frame, 
            text="选择颜色", 
            command=lambda: self.choose_text_color(text_color_preview, text_color_code_label, self.text_color_var)
        ).pack(side=tk.LEFT)
        
        # 透明度设置
        transparency_frame = ttk.LabelFrame(self, text="窗口透明度", padding=10)
        transparency_frame.pack(fill=tk.X, padx=10, pady=5)
        
        # 转换存储的透明度值为百分比
        transparency_value = float(self.config['SETTINGS'].get('transparency', '1.0')) * 100
        self.transparency_var = tk.IntVar(value=int(transparency_value))
        
        # 透明度滑块和值显示框架
        transparency_control_frame = ttk.Frame(transparency_frame)
        transparency_control_frame.pack(fill=tk.X)
        
        transparency_scale = ttk.Scale(
            transparency_control_frame, 
            from_=30, 
            to=100, 
            variable=self.transparency_var,
            orient=tk.HORIZONTAL
        )
        transparency_scale.pack(side=tk.LEFT, fill=tk.X, expand=True)
        
        # 显示百分比值
        transparency_value_label = ttk.Label(
            transparency_control_frame, 
            text=f"{self.transparency_var.get()}%",
            width=5
        )
        transparency_value_label.pack(side=tk.RIGHT, padx=(10, 0))
        
        # 绑定事件以更新标签
        transparency_scale.configure(
            command=lambda v: transparency_value_label.config(text=f"{int(float(v))}%")
        )
        
        # 窗口置顶设置
        topmost_frame = ttk.LabelFrame(self, text="窗口行为", padding=10)
        topmost_frame.pack(fill=tk.X, padx=10, pady=5)
        
        self.topmost_var = tk.BooleanVar(value=self.config['SETTINGS'].getboolean('always_on_top', False))
        ttk.Checkbutton(
            topmost_frame, 
            text="窗口始终置顶", 
            variable=self.topmost_var
        ).pack(anchor=tk.W)
        
        # 按钮
        button_frame = ttk.Frame(self)
        button_frame.pack(fill=tk.X, padx=10, pady=10)
        
        ttk.Button(
            button_frame, 
            text="保存", 
            command=self.on_save
        ).pack(side=tk.RIGHT, padx=(5, 0))
        
        ttk.Button(
            button_frame, 
            text="预览", 
            command=self.on_preview
        ).pack(side=tk.RIGHT, padx=(5, 0))
        
        ttk.Button(
            button_frame, 
            text="取消", 
            command=self.on_cancel
        ).pack(side=tk.RIGHT)
    
    def choose_color(self, preview_frame, code_label, color_var):
        """选择颜色并更新预览和代码显示"""
        color = colorchooser.askcolor(initialcolor=color_var.get())
        if color[1]:
            color_var.set(color[1])
            preview_frame.configure(background=color[1])
            code_label.config(text=color[1])
    
    def choose_text_color(self, preview_frame, code_label, color_var):
        """选择文本颜色并更新预览和代码显示"""
        color = colorchooser.askcolor(initialcolor=color_var.get())
        if color[1]:
            color_var.set(color[1])
            preview_frame.configure(background=color[1])
            code_label.config(text=color[1], foreground=color[1])
    
    def on_preview(self):
        """预览设置效果（仅应用于当前窗口）"""
        # 创建临时设置字典
        preview_settings = {
            'background_color': self.bg_color_var.get(),
            'foreground_color': self.fg_color_var.get(),
            'text_color': self.text_color_var.get(),
            'transparency': str(self.transparency_var.get() / 100.0),
            'always_on_top': str(self.topmost_var.get())
        }
        
        # 应用设置到当前窗口
        apply_settings(self, preview_settings)
    
    def on_save(self):
        """保存设置"""
        # 禁用按钮防止重复点击
        self.grab_release()
        
        # 保存设置
        self.save_settings()
        
        # 销毁窗口
        self.destroy()
        
        # 显示成功消息
        messagebox.showinfo("成功", "设置已保存，重启程序后生效")
    
    def on_cancel(self):
        """取消设置"""
        self.destroy()